﻿using System;
using System.Web.Mvc;

namespace MvcContrib.Shp.UI
{
    /// <summary>
    /// Contains extention methods for <see cref="System.Web.Mvc.HtmlHelper"/>
    /// </summary>
    public static class HtmlHelperExtensions
    {
        private static readonly string FactoryKey = typeof (MvcContribUIComponentFactory).AssemblyQualifiedName;

        /// <summary>
        /// Gets the MvcContrib UI Component Factory <see cref="MvcContribUIComponentFactory"/>.
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <returns></returns>
        public static MvcContribUIComponentFactory MvcContrib(this HtmlHelper htmlHelper)
        {
            if (htmlHelper == null)
                throw new ArgumentNullException("htmlHelper");

            var factory = htmlHelper.ViewContext.HttpContext.Items[FactoryKey] as MvcContribUIComponentFactory;

            if (factory == null)
            {
                factory = new MvcContribUIComponentFactory(htmlHelper);
                htmlHelper.ViewContext.HttpContext.Items[FactoryKey] = factory;
            }
            else
            {
                factory.HtmlHelper = htmlHelper;
            }

            return factory;
        }
    }
}